// slbModel.go
package models

import (
	"errors"
	//"fmt"

	"fmt"
	"log"

	//"time"

	//"strconv"

	"github.com/beego/beego/v2/client/orm"
	"github.com/beego/beego/v2/core/validation"
)

type Limitwhite struct {
	Id         int64  `json:"id"`
	Appname    string `json:"appname" valid:"Required"`
	Ruletype   string `json:"ruletype" valid:"Required"`
	Ruleitem   string `json:"ruleitem" valid:"Required"`
	Enable     bool   `json:"enable"`
	Remarks    string `json:"remarks"`
	Updatetime string `json:"updatetime"`
	Createtime string `json:"createtime"`
}

func init() {
	orm.Debug = true
	//orm.RegisterModel(new(Limitrule)) //因为configModel中已注册，无法重复注册，即使更改结构体名称
}

func (u *Limitwhite) TableName() string {
	return "xf_reqlimit_white_list"
}

func checkRwl(u *Limitwhite) (err error) {
	valid := validation.Validation{}
	b, _ := valid.Valid(&u)
	if !b {
		for _, err := range valid.Errors {
			log.Println(err.Key, err.Message)
			return errors.New(err.Message)
		}
	}
	return nil
}

//List
func GetRwlList(appname string, id int64) (xlr []*Limitwhite, count int64) {
	o := orm.NewOrm()
	var sqlstr string
	if id > 0 {
		sqlstr = fmt.Sprintf("select * from xf_reqlimit_white_list where id = '%d'", id)
	}
	if appname != "" {
		sqlstr = fmt.Sprintf("select * from xf_reqlimit_white_list where appname = '%s' ORDER BY id DESC", appname)
	}
	num, err2 := o.Raw(sqlstr).QueryRows(&xlr)
	if err2 != nil {
		log.Println(err2)
	}
	return xlr, num
}

//添加
func AddRwl(u *Limitwhite) (int64, error) {
	if err := checkRwl(u); err != nil {
		return 0, err
	}
	o := orm.NewOrm()
	var numt int64
	res, err := o.Raw(`insert into xf_reqlimit_white_list(appname,ruletype, ruleitem,remarks)values(?,?,?,?)`, u.Appname, u.Ruletype, u.Ruleitem, u.Remarks).Exec()
	if err != nil {
		log.Printf("[ERROR] Add LimitRule err:%s\n", err)
		return 0, err
	}
	Id, _ := res.LastInsertId()
	if Id > 0 {
		numt++
	}
	UpdateConfigTime(u.Appname)
	return numt, nil
}

func DelByRwlId(id int64, appname string) (int64, error) {
	o := orm.NewOrm()
	res, err := o.Raw(`DELETE FROM xf_reqlimit_white_list WHERE id = ?`, id).Exec()
	if err != nil {
		log.Printf("[ERROR] Del LimitRule err:%s\n", err)
		return 0, err
	}
	num, err := res.RowsAffected()
	if err != nil {
		log.Printf("[ERROR] Del customurlFail3 err:%s\n", err)
		return 0, err
	}
	UpdateConfigTime(appname)
	return num, nil
}

func EditRwl(id, appname, key, value string) (int64, error) {
	o := orm.NewOrm()
	sqlstr := fmt.Sprintf("UPDATE xf_reqlimit_white_list SET %s = '%s' WHERE id = %s AND appname = '%s'", key, value, id, appname)
	res, err := o.Raw(sqlstr).Exec()
	if err == nil {
		num, _ := res.RowsAffected()
		log.Printf("[INFO] EditLimitRule affected nums:%d\n", num)
		UpdateConfigTime(appname)
		return num, nil
	}
	return 0, err
}
